var mysql      = require('mysql');

function db(){
    //connection.end();
}

var connection = db.connection=mysql.createConnection({
    host     : '192.168.31.161',
    user     : 'root',
    password : '123456',
    database : 'playshow'
    });
    
    connection.connect();
    connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
        if (err) throw err;
        console.log('connect mysql ok .', rows[0].solution);
    });

    db.query=function(sql,func){
        return new Promise(function (resolve, reject){
            var query=connection.query(sql, function(err, rows, fields) {
                if (err) return reject(err);
                resolve(rows);
            });
            console.log(query.sql);
        })
       
    }

    db.insert=function(name,post,func){
        var query = connection.query('INSERT INTO '+name+' SET ?', post, function(err, result) {
                if (err) throw err;
                console.log(result.insertId);
                if(func) func(result.insertId);
          });
          console.log(query.sql);
    
       }
        db.close=function(){
            connection.end();
        }

        db.init=function(){
            connection.query("CREATE TABLE `plan` (\
                `id` INT not NULL AUTO_INCREMENT,\
                `name` VARCHAR(50) NULL COMMENT '名称',\
                `money_standard` FLOAT NULL COMMENT '标准价格',\
                `money_premium` FLOAT NULL COMMENT '保险价格',\
                `des` TEXT NULL COMMENT '描述',\
                `intime` INT NULL COMMENT '插入时间',\
                `uptime` INT NULL COMMENT '更新时间',\
                PRIMARY KEY (`id`));",function(err, rows, fields){
                    if(!err) throw err;
                    var time=new Date().getTime()/1000;
                    db.insert('plan',{name:"General",money_standard:0,money_premium:100,des:"123",intime:time,uptime:time});
                    db.insert('plan',{name:"Specialist",money_standard:20,money_premium:100,des:"123",intime:time,uptime:time});
                    db.insert('plan',{name:"Physiotherapy",money_standard:30,money_premium:88,des:"123",intime:time,uptime:time});                    
                    mydb.close();
                });
        }
    module.exports=db;
// extends.aa=11;